/**
 * Created by Administrator on 2017/10/20.
 */
public class SequenceList implements LinearList {
    private Object[] data;
    private int length=0;
     private static final int Empty =0;

    public SequenceList(int capacity) {
        this.data = new Object[capacity];
    }

    @Override
    public int length() {
        return length;
    }

    @Override
    public int search(Object element) {
        int k=0;
        while (k<length&&!data[k].equals(element))k++;
        if (k<length)
            return k;
        return -1;
    }

    @Override
    public Object getElementAt(int index) throws Exception {
        if (index<0||index>length)
            throw new Exception("下标非法");
        return data[index];
    }

    @Override
    public void insert(int index, Object element) throws Exception {
        if (isFull())
            throw new Exception("顺序表已满");
        if (index<0||index>length)
            throw new Exception("下标非法");
        for (int k=length;k>index;k--)
        {
            data[k]=data[k-1];
        }
        data[index]=element;
        length++;
    }

    @Override
    public Object remove(int index) throws Exception {
        Object tmp=null;
        if (index<0||index>length)
            throw new Exception("下标非法");
        tmp=data[index];
        for (int k=index;k<length-1;k++)
        {
            data[k]=data[k+1];
        }
        length--;
        return tmp;
    }

    @Override
    public boolean isEmpty(){
        return length==Empty;
    }

    @Override
    public boolean isFull() {
        return length== data.length;
    }

    @Override
    public void clear() {
        length=0;
    }

    @Override
    public void showList() {

        for (Object item:data) {
            System.out.print(item.toString()+",");
        }
        System.out.println();
    }
}
